//
//  ConfigureItemViewController.m
//  ws-mgmt-client
//
//  Created by Cliff Duffey on 9/14/09. Mage Labs.
//

#import "ConfigureItemViewController.h"
#import "ConfigureServerViewController.h"
#import "ServerRootViewController.h"
#import "ws_mgmt_clientAppDelegate.h"
#import "RootViewController.h"

@implementation ConfigureItemViewController
@synthesize labelText;
@synthesize text;

#pragma mark Button Responder Methods

//Make the keyboard disappear when user presses down outside of the keyboard
- (IBAction) resignKeyBoard: (id) sender
{
	[text resignFirstResponder];
}

//Save the new config item when in the server root
- (void) buttonPressedForServerRoot
{
	ws_mgmt_clientAppDelegate *delegate = [[UIApplication sharedApplication] delegate];

	//Find the previous view controller in the nav view stack
	NSArray *viewArray = [delegate.navigationController viewControllers];
	ServerRootViewController *prevController = (ServerRootViewController *)[viewArray objectAtIndex: [viewArray count] - 2];
	
	NSString *itemToChange = text.text; //get the string from the text box
	
	//Update the correct config item in the ConfigureServerViewController
	if( [labelText compare:@"URL"] == NSOrderedSame )
	{			
		if( [NSURL URLWithString:itemToChange] ) //Make sure it's a valid URL
		{ 
			prevController.firstTabController.url = itemToChange;
			NSLog(@"%@ is a valid URL", prevController.firstTabController.url);
		} else {
			NSLog(@"%@ not a valid URL!", itemToChange);
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid URL" 
															message:@"You selected an invalid URL." 
														   delegate:nil 
												  cancelButtonTitle:@"Close" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
		}

	} 
	else if( [labelText compare:@"Name"] == NSOrderedSame )
	{
		
		prevController.firstTabController.name = itemToChange;
					
	}
	else if( [labelText compare:@"Username"] == NSOrderedSame )
	{
		prevController.firstTabController.username = itemToChange;
	} else if( [labelText compare:@"Password"] == NSOrderedSame ){
		prevController.firstTabController.password = itemToChange;
	}
	else {
		NSLog(@"Label text must have been corrupted.");
	}
	
	
	[prevController.firstTabController save]; //Save the new config item
	[prevController.firstTabController.tableView reloadData]; //Refresh the config items on the ConfigView table
			
	//Go back to the previous view
	[delegate.navigationController popViewControllerAnimated:YES]; 

}

//Save the new config item when in root
- (void) buttonPressedForRoot
{
	ws_mgmt_clientAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	
	//Find the previous view controller in the nav view stack
	NSArray *viewArray = [delegate.navigationController viewControllers];
	ConfigureServerViewController *prevController = (ConfigureServerViewController *)[viewArray objectAtIndex: [viewArray count] - 2];
	
	NSString *itemToChange = text.text; //get the string from the text box
	
	//Update the correct config item in the ConfigureServerViewController
	if( [labelText compare:@"URL"] == NSOrderedSame )
	{			
		if( [NSURL URLWithString:itemToChange] ) //Make sure it's a valid URL
		{ 
			prevController.url = itemToChange;
			NSLog(@"%@ is a valid URL", prevController.url);
		} else {
			NSLog(@"%@ not a valid URL!", itemToChange);
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid URL" 
															message:@"You selected an invalid URL." 
														   delegate:nil 
												  cancelButtonTitle:@"Close" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
		}
		
	} 
	else if( [labelText compare:@"Name"] == NSOrderedSame )
	{
		
		prevController.name = itemToChange;
		
	}
	else if( [labelText compare:@"Username"] == NSOrderedSame )
	{
		prevController.username = itemToChange;
	} else if( [labelText compare:@"Password"] == NSOrderedSame ){
		prevController.password = itemToChange;
	}
	else {
		NSLog(@"Label text must have been corrupted.");
	}
	
	[prevController save]; //Save the new config item
	[prevController.tableView reloadData]; //Refresh the config items on the ConfigView table
	
	//Go back to the previous view
	[delegate.navigationController popViewControllerAnimated:YES]; 
	
}

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

	ws_mgmt_clientAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	
	//Find the root view controller in the nav view stack to find out value of inRoot
	NSArray *viewArray = [delegate.navigationController viewControllers];
	RootViewController *prevController = (RootViewController *)[viewArray objectAtIndex: 0];
	
	BOOL _inRoot = prevController.inRoot;
	
	self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
	
	NSString *tempTitle = [[NSString alloc] initWithFormat: @"Edit %@", self.labelText];
	self.title = tempTitle;
	

	if([self.labelText compare: @"Password"] == NSOrderedSame) //Don't want to show the password
		self.text.secureTextEntry = TRUE;
	
	[self.text becomeFirstResponder];
	
	
	if( _inRoot ) {
		//Add a system 'Save' button to the right; change selector whether from ServerRoot or Root
		UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
									   initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(buttonPressedForRoot)];	
		self.navigationItem.rightBarButtonItem = saveButton;
		[saveButton release];
	}
	else {
		UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
									   initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(buttonPressedForServerRoot)];	
		self.navigationItem.rightBarButtonItem = saveButton;
		[saveButton release];
	}

	[tempTitle release];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[labelText release];
	[text release];
    [super dealloc];
}


@end
